<?php
/**
 * KvFramework module base class
 * @package KvFramework_v2
 * @subpackage KvF_ModuleHandler
 * @author Greg McWhirter <gsmcwhirter@gmail.com>
 * @copyright Copyright &copy; 2006, Greg McWhirter
 * @version $Revision$
 */

load_files(
  KVF_FRAMEWORK."/kvf_modulehandler/interfaces/kvf_action.interface.php",
  KVF_FRAMEWORK."/kvf_modulehandler/kvf_action.class.php",
  KVF_FRAMEWORK."/kvf_modulehandler/exceptions/kvf_module.exception.php"
);

/**
 * Module base class
 * @package KvFramework_v2
 * @subpackage KvF_ModuleHandler
 */
abstract class KvfModule extends KvfBase
{

  protected static $_LayoutParams = array();

  public static function GetLayoutParams()
  {
    return self::$_LayoutParams;
  }

  /**
   * Perform an action from this module
   *
   * @param string $action
   * @param string $requestmethod
   */
  public function DoAction($action, $requestmethod)
  {
    $class = get_class($this);
    $fsc = null;

    while($class != "KvfModule" && substr($class, -6) == "Module" && is_null($fsc))
    {
      $class2 = self::$INFLECTOR->Camel2Underscore($class);
      $act = self::$INFLECTOR->Camel2Underscore($action);
      $f = KVF_MODULES."/".substr($class2, 0, -7).".module/actions/".$act.".action.php";
      if(file_exists($f))
      {
        $fsc = self::$INFLECTOR->Underscore2Camel($class2)."_".self::$INFLECTOR->Underscore2Camel($action."_action");
      }
      else
      {
        $class = get_parent_class($class);
      }
    }

    if(is_null($fsc))
    {
      throw new KvfModuleException("Unable to find requested action ".$action." (".$act." : ".$f.").", KvfModuleException::ActionNotFound);
    }

    #try
    #{
      $this->BeforeFilters();
      $actioninst = new $fsc($this, $requestmethod);

      try
      {
        $actioninst->BeforeFilters();
        if(!$actioninst->IsRedirected())
        {
          $actioninst->Validate();
        }
        if(!$actioninst->IsRedirected())
        {
          $actioninst->Process();
        }
      }
      catch(KvfModuleException $e)
      {
        /*foreach($e->Errors as $err)
        {
          self::Error($err);
        }*/

        if(!$actioninst->IsRedirected())
        {
          $actioninst->HandleError($e->getCode(), $e->getMessage());
        }
      }

      $data = "";

      if(!$actioninst->IsRedirected())
      {
        ob_start();
        $actioninst->Display();
        $actioninst->AfterFilters();
        $data = ob_get_contents();
        ob_end_clean();

        $this->AfterFilters();

      }
      $k = substr($class, 0, -6);
      return array($data, $k, $actioninst->IsRedirected());
    #}
    #catch(KvfModuleException $e)
    #{
    #
    #}
  }

  /**
   * Executes arbitrary commands before the action instance is created.
   *
   */
  protected function BeforeFilters()
  {}

  /**
   * Executes arbitrary commands after the action instance has been completed.
   *
   */
  protected function AfterFilters()
  {}

}
?>
